package com.ljl.question2;

import com.ljl.question2.tcp.TcpConnector;
import com.ljl.question2.tcp.TcpConnectorEntityVo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 控制器
 *
 * @author ljl
 */
@RestController
@RequestMapping("/api/tcp")
public class ManagerController implements ApplicationContextAware {
    /**
     * 上下文
     */
    private ApplicationContext applicationContext;

    private static final ConcurrentHashMap<String, TcpConnector> map = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @GetMapping
    public ResponseEntity<Object> findAll() {
        List<TcpConnectorEntityVo> collect = map.values().stream().map(item -> {
            TcpConnectorEntityVo vo = new TcpConnectorEntityVo();
            vo.setUuid(item.getUuid());
            vo.setIp(item.getIp());
            vo.setPort(item.getPort());
            vo.setCounter(item.getCounter());
            return vo;
        }).toList();
        return new ResponseEntity<>(collect, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<Object> createConnector(@RequestBody Map<String, Object> body) {
        try {
            String key = UUID.randomUUID().toString();
            body.put("uuid", key);
            TcpConnector tcpConnector = (TcpConnector) ReflectUtil.createObject("com.ljl.question2.tcp.TcpConnector", body);
            tcpConnector.start();
            map.put(key, tcpConnector);
        } catch (Exception e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PutMapping
    public ResponseEntity<Object> updateConnect(@RequestBody Map<String, Object> body) {
        String uuid = (String) body.get("uuid");
        TcpConnector connector = map.get(uuid);
        try {
            ReflectUtil.updateProperties(connector, body);
            connector.start();
        } catch (Exception e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
